<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;

class Category extends Model
{
    protected $guarded = [];

    public function children()
    {
        return $this->hasMany('App\Category', 'parent_id', 'id');
    }

    public function descendants()
    {
        return $this->children()->with('descendants');
    }

    public function parent()
    {
        return $this->belongsTo('App\Category', 'parent_id', 'id');
    }

    public static function tree($collection, $pid = 0, $flg = '└─')
    {
        global $tree;
        foreach ($collection as $key => $val) {
            if ($val['parent_id'] == $pid) {
                $tempFlg = str_repeat($flg, $val['depth']);
                $val['name'] = $tempFlg . $val['name'];
                $tree[] = $val;
                self::tree($collection, $val['id'], $flg);
            }
        }
        return $tree;
    }

    public static function treeData($collection, $pk = 'id', $pid = 'parent_id', $children = 'children', $root = 0)
    {
        $tree = [];
        foreach ($collection as $key => $val) {
            if ($val[$pid] == $root) {
                // 获取当前$pid所有子类
                unset($collection[$key]);
                if (count($collection) > 0) {
                    $childrenData = self::treeData($collection, $pk, $pid, $children, $val[$pk]);
                    if (count($childrenData) > 0) {
                        $val[$children] = $childrenData;
                    }
                }
                $tree[] = $val;
            }
        }
        return $tree;
    }

    public function goods()
    {
        return $this->hasMany('App\Goods');
    }
}